package com.atguigu.yygh.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.hosp.repository.ScheduleRepository;
import com.atguigu.yygh.hosp.service.DeparmentService;
import com.atguigu.yygh.hosp.service.HospitalService;
import com.atguigu.yygh.hosp.service.ScheduleService;
import com.atguigu.yygh.model.hosp.Department;
import com.atguigu.yygh.model.hosp.Schedule;
import com.atguigu.yygh.vo.hosp.BookingScheduleRuleVo;
import com.atguigu.yygh.vo.hosp.ScheduleOrderVo;
import io.swagger.annotations.ApiOperation;
import org.joda.time.DateTime;
import org.joda.time.DateTimeConstants;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ScheduleServiceImol  implements ScheduleService {

    @Autowired
    private ScheduleRepository scheduleRepository;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private DeparmentService  deparmentService;

    @Override
    public void save(Map<String, Object> param) {
        String mapString = JSONObject.toJSONString(param);

        Schedule schedule = JSONObject.parseObject(mapString, Schedule.class);

        Schedule scheduleOne = scheduleRepository.getByHoscodeAndHosScheduleId(schedule.getHoscode(), schedule.getHosScheduleId());

        if (scheduleOne != null) {
            scheduleOne.setUpdateTime(new Date());
            scheduleOne.setIsDeleted(0);
            scheduleOne.setStatus(1);
            scheduleRepository.save(scheduleOne);

        } else {
            schedule.setStatus(1);
            schedule.setIsDeleted(0);
            schedule.setUpdateTime(new Date());
            schedule.setCreateTime(new Date());

            scheduleRepository.save(schedule);

        }
    }

    @Override
    public String getSignKey(String hoscode) {
        return null;
    }

    @Override
    public Page<Schedule> findPageScheduleOrder(int page, int limit, ScheduleOrderVo scheduleOrderVo) {
        //创建Pageable对象 设置当前页和每页记录数
        Pageable pageable = PageRequest.of(page - 1, limit);

        Schedule schedule = new Schedule();

        BeanUtils.copyProperties(scheduleOrderVo, schedule);
        schedule.setIsDeleted(0);
        //创建 Example 对象
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                .withIgnoreCase(true);

        Example<Schedule> example = Example.of(schedule, matcher);

        Page<Schedule> all = scheduleRepository.findAll(example, pageable);

        return all;
    }

    @Override
    public void remove(String hoscode, String hosScheduleId) {

        Schedule sch = scheduleRepository.getByHoscodeAndHosScheduleId(hoscode, hosScheduleId);
        if (sch != null) {

            scheduleRepository.deleteById(sch.getId());
        }
    }

    @Override
    public Map<String, Object> getRuleSchedule(Long page, Long limit, String hoscode, String depcode) {

        //更具医院编号 和科室编号查询

        Criteria criteria = Criteria.where("hoscode").is(hoscode).and("depcode").is(depcode);


        //更具工作日期分组
        Aggregation agg = Aggregation.newAggregation(

                Aggregation.match(criteria),
                Aggregation.group("workDate")
                        .first("workDate").as("workDate")
                        //统计号源数量
                        .count().as("docCount")
                        .sum("reservedNumber").as("reservedNumber")
                        .sum("availableNumber").as("availableNumber"),
                //排序
                Aggregation.sort(Sort.Direction.DESC, "workDate"),
                //分页
                Aggregation.skip((page - 1) * limit),
                Aggregation.limit(limit)

        );
        //调用方法，最终执行
        AggregationResults<BookingScheduleRuleVo> aggregate = mongoTemplate.aggregate(agg, Schedule.class, BookingScheduleRuleVo.class);

        List<BookingScheduleRuleVo> mappedResults = aggregate.getMappedResults();


        //分组查询总记录数
        Aggregation totalAgg = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group("workDate")


        );
        AggregationResults<BookingScheduleRuleVo> totalAggResult =
                mongoTemplate.aggregate(totalAgg, Schedule.class, BookingScheduleRuleVo.class);

        int total = totalAggResult.getMappedResults().size();

        //把日期对应星期几获取
        for (BookingScheduleRuleVo bookingScheduleRuleVo : mappedResults) {
            Date workDate = bookingScheduleRuleVo.getWorkDate();

            String dayOfWeek = this.getDayOfWeek(new DateTime(workDate));

            bookingScheduleRuleVo.setDayOfWeek(dayOfWeek);

        }
 // 设置最终数据 进行返回
        Map<String,Object> result=new HashMap<>();
        result.put("bookingScheduleRuleList",mappedResults);
        result.put("total",total);

        // 获取医院名称
       String hospName =hospitalService.getHospName(hoscode);
  Map<String,String> baseMap=new HashMap<>();
    baseMap.put("hosname",hospName);
    result.put("baseMap",baseMap);

        return result;
    }

    @Override
    public List<Schedule> getDetailScheduls(String hoscode, String depcode, String workDate) {

      List<Schedule> schedule =scheduleRepository.findScheduleByHoscodeAndDepcodeAndWorkDate(hoscode,depcode,new DateTime(workDate).toDate());
        schedule.stream().forEach(item->{

            this.packgeSchedule(item);

        });

      return schedule;
    }
 //封装排班详情其他值
    private void packgeSchedule(Schedule item) {

        //设置医院名称

        item.getParam().put("hosname",hospitalService.getHospName(item.getHoscode()));

        item.getParam().put("depname",deparmentService.getDepName(item.getHoscode() ,item.getDepcode()));

        item.getParam().put("dayOfWeek",this.getDayOfWeek(new DateTime(item.getWorkDate()).toDateTime()));


    }

    @Autowired
private HospitalService hospitalService;

    private String getDayOfWeek(DateTime dateTime) {
        String dayOfWeek = "";
        switch (dateTime.getDayOfWeek()) {
            case DateTimeConstants.SUNDAY:
                dayOfWeek = "周日";
                break;
            case DateTimeConstants.MONDAY:
                dayOfWeek = "周一";
                break;
            case DateTimeConstants.TUESDAY:
                dayOfWeek = "周二";
                break;
            case DateTimeConstants.WEDNESDAY:
                dayOfWeek = "周三";
                break;
            case DateTimeConstants.THURSDAY:
                dayOfWeek = "周四";
                break;
            case DateTimeConstants.FRIDAY:
                dayOfWeek = "周五";
                break;
            case DateTimeConstants.SATURDAY:
                dayOfWeek = "周六";
            default:
                break;
        }

        return dayOfWeek;
    }

}

